import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Reg from "../views/Reg.vue";
import Dashboard from '../views/Dashboard.vue'
import Articles from '../views/Articles.vue'
import Categories from '../views/Categories.vue'
import Comments from '../views/Comments.vue'
import AnnexPages from "../views/AnnexPages.vue";
// import { component } from 'vue/types/umd'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/reg',
    name: 'Reg',
    component: Reg
  },
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    redirect: '/articles',
    children: [
      {
        path: 'articles',
        name: 'Articles',
        component: Articles
      },
      {
        path: 'articles/edit/:id?',
        name: 'ArticleEdit',
        component: () => import('../views/ArticleEdit.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'categories',
        name: 'Categories',
        component: Categories
      },
      {
        path: 'comments',
        name: 'Comments',
        component: Comments
      },
      {
        path: '/annexPages',
        name: 'AnnexPages',
        component: AnnexPages
      },
      {
        path: 'notes',
        name: 'Notes',
        component: () => import('../views/Notes.vue')
      },
      {
        path: 'notes/edit/:id?',
        name: 'NoteEdit',
        component: () => import('../views/NoteEdit.vue')
      },
      {
        path: 'projects',
        name: 'Projects',
        component: () => import('../views/Projects.vue')
      },
      {
        path: 'projects/edit/:id?',
        name: 'ProjectEdit',
        component: () => import('../views/ProjectEdit.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  // 不需要登录的页面
  const publicPages = ['/login', '/reg'];
  const authRequired = !publicPages.includes(to.path);

  const token = localStorage.getItem('token')

  if (authRequired && !token) {
    // 未登录，强制跳转到登录页
    return next('/login');
  }

  next()
})

export default router
